#!/usr/bin/env python
# -*- coding: utf-8 -*-

from tornado.web import RequestHandler
from util import cache, settings

import pymongo
import re
import render
import codecs
import MySQLdb

def sub(x, y):
    return x - y

class Manage(RequestHandler):
    def get(self):
        _pagenum = 10
        _page = self.get_argument('page', '1') #页码
        _factory = self.get_argument('factory', '').strip() #厂商
        _os = self.get_argument('os', '').strip() #操作系统
        _brand = self.get_argument('brand', '').strip() #终端类型 1：智能机 2：低端机 3：Pad
        _mode = self.get_argument('mode', '').strip() #合作模式  1：广告  2：下载 3：渠道 4：自用 5：内置
        
        if not _page.isdigit():
            _page = 1
        else:
            _page = int(_page)
        
        cache_data_key = '{0}/{1}/{2}/{3}/{4}'.format(_factory, _os, _brand, _mode, _page)
        cache_page_key = 'page/{0}/{1}/{2}/{3}/{4}'.format(_factory, _os, _brand, _mode, _page)
#        
#        cache.add('pid_cache_os',{}, settings.cache_expire_S)
#        cache.add('pid_cache_factory',{}, settings.cache_expire_S)
#        cache.add('pid_cache_page',{}, settings.cache_expire_S)
#        cache.add('pid_cache_os_m',{}, settings.cache_expire_S)
#        cache.add(cache_key,[], settings.cache_expire_S)
        
        os = cache.get('pid_cache_os') or {}
        factory = cache.get('pid_cache_factory') or {}
        os_m = cache.get('pid_cache_os_m') or {}#key=value
        pid_arr = cache.get(cache_data_key) or []
        page = cache.get(cache_page_key) or {}
        
#        os = {}
#        factory = {}
#        page = {}
#        os_m = {}
#        pid_arr = []
        
        
        mode = {'1':'广告', '2':'下载', '3':'渠道', '4':'自用（默认）', '5':'内置', '6':'链接跳转'}
        brand = {'1':'智能机（默认）', '2':'低端机','3':'平板电脑','4':'机顶盒'}      
        
        print pid_arr
        if os and factory and pid_arr and page:
            self.render('templates/pid-manage.html', page=page, p_page=_page, p_os=_os, p_factory=_factory, p_brand=_brand, p_mode=_mode, os=os, factory=factory, brand=brand, mode=mode, pid_arr=pid_arr)
            return
        
        mysql_config = settings.mysql_config
        
        dbMysql=MySQLdb.connect(**mysql_config)
        c=dbMysql.cursor()
        
        if not os : 
            sql_os = "SELECT id, name FROM  `s_os` "
            c.execute(sql_os)
            os_fet = c.fetchall()
            for x in os_fet:
                os[x[1]] = '{0},{1}'.format( os.get(x[1],''), x[0]) 
                os_m[x[0]] = x[1] 
            cache.add('pid_cache_os', os, settings.cache_expire_S)
            cache.add('pid_cache_os_m', os_m, settings.cache_expire_S)
            print '2222222222{0}'.format(os)        
        
        if not factory : 
            sql_factory = "SELECT id, name_cn FROM  `s_factory` "
            c.execute(sql_factory)
            factory_fet = c.fetchall()
            for x in factory_fet:
                factory[x[0]] = x[1]
            cache.add('pid_cache_factory', factory, settings.cache_expire_S)
            print '3333333333{0}'.format(os)        
        
        factory_sql_query = ''
        if _factory :
            factory_sql_query = 'and f_id={0}'.format(_factory)
        
        os_sql_query = ''
        if _os :
            os_sql_query = 'and os_id in ({0})'.format(_os[1:])
            
        mode_sql_query = ''
        if _mode :
            mode_sql_query = 'and partner_mode = {0}'.format(_mode)
            
        brand_sql_query = ''
        if _brand :
            brand_sql_query = 'and brand_type = {0}'.format(_brand)
        
        pid_arr = []
        
        sql = u"SELECT count(pid) FROM  `s_partner` WHERE 1=1 {0} {1} {2} {3}".format(factory_sql_query,os_sql_query, mode_sql_query, brand_sql_query)
        c.execute(sql)  
        count_fet = c.fetchall()
        count = [x[0] for x in count_fet]
        if len(count) == 1:
            count = int(count[0])
        else:
            count = 0

        page['count'] = count
        page['total'] = count/_pagenum + 1 
        page['first'] = 1
        page['next'] = page['total'] if _page + 1 > page['total'] else _page+1
        page['previous'] = _page -1 if _page  > 1 else 1
        page['last'] = count/_pagenum + 1 
        cache.add(cache_page_key, page, settings.cache_expire_S)
        print page 
        sql = u"SELECT pid, f_id, os_id, partner_mode, brand_type FROM  `s_partner` WHERE 1=1 {0} {1} {2} {3}".format(factory_sql_query,os_sql_query, mode_sql_query, brand_sql_query)
        sql = sql + ' limit {0}, {1}'.format((_page-1)*_pagenum, _pagenum)
        print sql
        c.execute(sql)  
        pid_fet = c.fetchall()
        for x in pid_fet:
            pid = {}
            pid['pid'] = x[0] 
            pid['f_id'] =  factory.get(x[1], 'NULL')
            pid['os_id'] = ([ key for key, value in os.items() if str(x[2]) in value] or [''])[0]
            pid['mode'] = mode.get(str(x[3]), '无')
            pid['brand'] = brand.get(str(x[4]), '无')
            pid_arr.append(pid)
        
        print cache_data_key  
        cache.add(cache_data_key, pid_arr, settings.cache_expire_S)
        
        self.render('templates/pid-manage.html', page=page, p_page=_page, p_os=_os, p_factory=_factory, p_brand=_brand, p_mode=_mode, os=os, factory=factory, brand=brand, mode=mode, pid_arr=pid_arr)
